package cConfig

import (
	"os"
	"path/filepath"
	"strings"

	"gitee.com/csingo/cLog"
)

type FileClient struct {
	Namespace string `json:"namespace"`
	Path      string `json:"path"`
}

func (i *FileClient) Driver() ConfigCenterDriver {
	return FileDriver
}

func (i *FileClient) InitClient() error {
	return nil
}

func (i *FileClient) ReadConf(id, group string, explain bool) (result string, err error) {
	if i.Path == "" {
		i.Path, err = os.Getwd()
		if err != nil {
			return
		}
	}
	if !filepath.IsAbs(i.Path) {
		var currentPath string
		currentPath, err = os.Getwd()
		if err != nil {
			return
		}
		i.Path = filepath.Join(currentPath, i.Path)
	}

	var filenameBuilder strings.Builder
	filenameBuilder.WriteString(id)
	filenameBuilder.WriteString(".")
	if group != "" {
		filenameBuilder.WriteString(group)
		filenameBuilder.WriteString(".")
	}
	if i.Namespace != "" {
		filenameBuilder.WriteString(i.Namespace)
		filenameBuilder.WriteString(".")
	}
	filenameBuilder.WriteString("json")
	filename := filenameBuilder.String()
	fullPath := filepath.Join(i.Path, filename)

	var resultBytes []byte
	resultBytes, err = os.ReadFile(fullPath)
	result = string(resultBytes)
	if err != nil {
		cLog.WithContext(nil, map[string]any{
			"source": "cConfig.FileClient.ReadConf",
			"file":   fullPath,
			"err":    err.Error(),
			"driver": i.Driver(),
		}, []cLog.Option{
			cLog.IncludePaths{},
		}).Error("配置读取异常")
		return
	} else {
		cLog.WithContext(nil, map[string]any{
			"source": "cConfig.FileClient.ReadConf",
			"file":   fullPath,
			"driver": i.Driver(),
		}, []cLog.Option{
			cLog.IncludePaths{},
		}).Trace("配置读取成功")
	}

	if !explain {
		return
	}

	var counter int64
	var matches []*ExplainItem
	for counter = 0; counter < config_center_config.Layers; counter++ {
		matches, err = Explain(i, result)
		if err != nil {
			return
		}
		if len(matches) == 0 {
			break
		}
		for _, item := range matches {
			result = item.ReplaceFunc(result, item.Source, item.Target)
		}
	}

	return
}
